<template>
  <div class="app-container">
    <!-- 标题区域 -->
    <div class="header">
      <div class="header-left">
        <h1>短剧用户深度分析看板</h1>
        <p>基于用户行为画像数据的多维度深度分析：用户分层、付费行为、观看习惯、内容偏好等</p>
      </div>
      <div class="header-right">
        <el-button
          type="primary"
          @click="refreshData"
          :loading="loading"
        >
          <i class="el-icon-refresh"></i> 刷新数据
        </el-button>
        <el-button @click="exportData">
          <i class="el-icon-download"></i> 导出报告
        </el-button>
        <el-select v-model="timeRange" placeholder="时间范围" style="width: 120px;">
          <el-option label="近7天" value="7"></el-option>
          <el-option label="近30天" value="30"></el-option>
          <el-option label="近90天" value="90"></el-option>
        </el-select>
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon user-icon">
              <i class="el-icon-user"></i>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ overview.totalUsers }}</div>
              <div class="stats-label">总用户数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon revenue-icon">
              <i class="el-icon-money"></i>
            </div>
            <div class="stats-info">
              <div class="stats-value">¥{{ overview.totalRevenue }}元</div>
              <div class="stats-label">总收入</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon payment-icon">
              <i class="el-icon-shopping-bag-1"></i>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ overview.paymentRate }}%</div>
              <div class="stats-label">付费率</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stats-icon completion-icon">
              <i class="el-icon-video-play"></i>
            </div>
            <div class="stats-info">
              <div class="stats-value">{{ overview.avgCompletion }}%</div>
              <div class="stats-label">平均完播率</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 7个可视化图表 -->
    <el-row :gutter="20" class="chart-row">
      <!-- 1. 用户分层金字塔图 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>用户分层金字塔</span>
            <el-tooltip content="展示不同层级用户的数量分布和核心指标" placement="top">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </div>
          <div id="userPyramidChart" class="chart-container" style="height: 400px;"></div>
        </el-card>
      </el-col>

      <!-- 2. 三维气泡图 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>性别-年龄-分层三维分析</span>
            <el-tooltip content="三维气泡图展示用户群体的交叉特征" placement="top">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </div>
          <div id="threeDimensionalChart" class="chart-container" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <!-- 3. 付费漏斗分析 -->
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>付费行为漏斗分析</span>
            <el-tooltip content="展示用户从浏览到付费的转化路径" placement="top">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </div>
          <div id="paymentFunnelChart" class="chart-container" style="height: 350px;"></div>
        </el-card>
      </el-col>

      <!-- 4. 观看场景热力图 -->
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>观看场景×时段热力图</span>
            <el-tooltip content="热力图展示不同场景和时段的观看密度" placement="top">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </div>
          <div id="watchHeatmapChart" class="chart-container" style="height: 350px;"></div>
        </el-card>
      </el-col>

      <!-- 5. 内容偏好桑基图 -->
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>内容偏好网络分析</span>
            <el-tooltip content="桑基图展示用户群体与内容主题的关联关系" placement="top">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </div>
          <div id="contentPreferenceChart" class="chart-container" style="height: 350px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <!-- 6. 用户生命周期分析 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>用户生命周期分析</span>
            <el-tooltip content="分析不同生命周期阶段的用户特征和价值" placement="top">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </div>
          <div id="userLifecycleChart" class="chart-container" style="height: 400px;"></div>
        </el-card>
      </el-col>

      <!-- 7. 收入贡献度帕累托图 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span>收入贡献度分析</span>
            <el-tooltip content="帕累托分析展示头部用户的收入贡献情况" placement="top">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </div>
          <div id="revenueContributionChart" class="chart-container" style="height: 400px;"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 加载状态 -->
    <el-dialog
      :visible.sync="loading"
      title="数据加载中"
      width="30%"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false">
      <div style="text-align: center;">
        <el-progress type="circle" :percentage="loadProgress"></el-progress>
        <p style="margin-top: 20px;">正在加载可视化数据...</p>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getEnhancedDashboardData } from '@/api/analysis/user-analysis'

export default {
  name: 'EnhancedUserAnalysis',
  data() {
    return {
      loading: false,
      loadProgress: 0,
      timeRange: '30',
      overview: {
        totalUsers: 0,
        totalRevenue: 0,
        paymentRate: 0,
        avgCompletion: 0
      },
      charts: {},
      dashboardData: {}
    }
  },
  mounted() {
    this.initCharts()
    this.loadData()
  },
  beforeDestroy() {
    Object.values(this.charts).forEach(chart => {
      if (chart) chart.dispose()
    })
  },
  methods: {
    // 初始化所有图表
    initCharts() {
      this.charts = {
        userPyramid: echarts.init(document.getElementById('userPyramidChart')),
        threeDimensional: echarts.init(document.getElementById('threeDimensionalChart')),
        paymentFunnel: echarts.init(document.getElementById('paymentFunnelChart')),
        watchHeatmap: echarts.init(document.getElementById('watchHeatmapChart')),
        contentPreference: echarts.init(document.getElementById('contentPreferenceChart')),
        userLifecycle: echarts.init(document.getElementById('userLifecycleChart')),
        revenueContribution: echarts.init(document.getElementById('revenueContributionChart'))
      }

      window.addEventListener('resize', this.handleResize)
    },

    // 加载数据
    async loadData() {
      this.loading = true
      this.loadProgress = 0

      try {
        const response = await getEnhancedDashboardData()
        this.dashboardData = response.data

        // 模拟加载进度
        const totalCharts = 7
        let loadedCharts = 0

        const progressInterval = setInterval(() => {
          loadedCharts++
          this.loadProgress = Math.min((loadedCharts / totalCharts) * 100, 90)
          if (loadedCharts >= totalCharts) {
            clearInterval(progressInterval)
            this.renderAllCharts()
            this.loadProgress = 100
            setTimeout(() => {
              this.loading = false
            }, 500)
          }
        }, 200)

        this.calculateOverview()
      } catch (error) {
        console.error('加载数据失败:', error)
        this.$message.error('数据加载失败')
        this.loading = false
      }
    },

    // 计算概览数据
    calculateOverview() {
      const pyramidData = this.dashboardData.userPyramid || []
      if (pyramidData.length > 0) {
        this.overview.totalUsers = pyramidData.reduce((sum, item) => sum + item.user_count, 0)
        this.overview.totalRevenue = pyramidData.reduce((sum, item) => sum + (item.total_revenue || 0), 0)

        // 使用实际的付费用户数计算付费率
        const paidUsers = pyramidData.reduce((sum, item) => sum + (item.paid_user_count || 0), 0)
        this.overview.paymentRate = ((paidUsers / this.overview.totalUsers) * 100).toFixed(1)

        this.overview.avgCompletion = (pyramidData.reduce((sum, item) => sum + item.avg_completion_rate, 0) / pyramidData.length).toFixed(1)
      }
    },

    // 渲染所有图表
    renderAllCharts() {
      this.renderUserPyramidChart()
      this.renderThreeDimensionalChart()
      this.renderPaymentFunnelChart()
      this.renderWatchHeatmapChart()
      this.renderContentPreferenceChart()
      this.renderUserLifecycleChart()
      this.renderRevenueContributionChart()
    },

    // 1. 用户分层金字塔图
    renderUserPyramidChart() {
      const data = this.dashboardData.userPyramid || []
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            const item = data.find(d => d.tier === params.name)
            return `${params.name}<br/>用户数: ${params.value}<br/>占比: ${params.percent}%<br/>平均付费: ¥${item.avg_payment}元<br/>总收入: ¥${item.total_revenue}元`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '用户数量'
        },
        yAxis: {
          type: 'category',
          data: data.map(item => item.tier).reverse(),
          axisLabel: {
            interval: 0,
            rotate: 0
          }
        },
        series: [{
          name: '用户数量',
          type: 'bar',
          data: data.map(item => ({
            value: item.user_count,
            name: item.tier,
            itemStyle: {
              color: this.getTierColor(item.tier)
            }
          })).reverse(),
          label: {
            show: true,
            position: 'right',
            formatter: '{c}人'
          }
        }]
      }
      this.charts.userPyramid.setOption(option)
    },

// 2. 三维气泡图 - 简化版（确保能显示）
    renderThreeDimensionalChart() {
      const data = this.dashboardData.threeDimensional || []

      // 使用简化数据格式测试
      const testData = [
        { gender: '女性', ageGroup: 'Z世代(18-25)', tier: '重度用户', user_count: 50 },
        { gender: '女性', ageGroup: '年轻上班族(26-35)', tier: '中度用户', user_count: 80 },
        { gender: '男性', ageGroup: 'Z世代(18-25)', tier: '轻度用户', user_count: 30 },
        { gender: '男性', ageGroup: '中年(36-45)', tier: '重度用户', user_count: 20 }
      ]

      const displayData = data.length > 0 ? data : testData

      const genders = [...new Set(displayData.map(item => item.gender))]
      const ageGroups = [...new Set(displayData.map(item => item.ageGroup))]

      const scatterData = displayData.map(item => {
        return {
          name: `${item.gender}-${item.ageGroup}`,
          value: [
            genders.indexOf(item.gender),
            ageGroups.indexOf(item.ageGroup),
            item.user_count
          ],
          user_count: item.user_count,
          tier: item.tier,
          avg_payment: item.avg_payment || 0
        }
      })

      const option = {
        tooltip: {
          trigger: 'item',
          formatter: function(params) {
            return `${params.data.name}<br/>用户数: ${params.data.user_count}<br/>层级: ${params.data.tier}<br/>平均付费: ¥${params.data.avg_payment}元`
          }
        },
        xAxis: {
          type: 'category',
          data: genders,
          name: '性别'
        },
        yAxis: {
          type: 'category',
          data: ageGroups,
          name: '年龄分组'
        },
        series: [{
          type: 'scatter',
          symbolSize: function(data) {
            return Math.max(20, data[2] / 2)
          },
          data: scatterData,
          itemStyle: {
            color: function(params) {
              const colors = {
                '忠实粉丝': '#e74c3c',
                '重度用户': '#e67e22',
                '中度用户': '#f1c40f',
                '轻度用户': '#2ecc71'
              }
              return colors[params.data.tier] || '#3498db'
            }
          }
        }]
      }

      this.charts.threeDimensional.setOption(option)
    },

    // 3. 付费漏斗图
    renderPaymentFunnelChart() {
      const data = this.dashboardData.paymentFunnel || []
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b} : {c} ({d}%)'
        },
        series: [{
          name: '付费漏斗',
          type: 'funnel',
          left: '10%',
          top: 60,
          bottom: 60,
          width: '80%',
          min: 0,
          max: data[0]?.user_count || 100,
          minSize: '0%',
          maxSize: '100%',
          sort: 'descending',
          gap: 2,
          label: {
            show: true,
            position: 'inside'
          },
          labelLine: {
            length: 10,
            lineStyle: {
              width: 1,
              type: 'solid'
            }
          },
          itemStyle: {
            borderColor: '#fff',
            borderWidth: 1
          },
          emphasis: {
            label: {
              fontSize: 20
            }
          },
          data: data.map(item => ({
            value: item.user_count,
            name: `${item.funnel_stage}\n${item.user_count}人\n${item.conversion_rate}%`
          }))
        }]
      }
      this.charts.paymentFunnel.setOption(option)
    },

    // 4. 观看热力图
    renderWatchHeatmapChart() {
      const data = this.dashboardData.watchHeatmap || []

      // 处理热力图数据
      const scenarios = [...new Set(data.map(item => item.scenario))]
      const timeSlots = [...new Set(data.map(item => item.timeSlot))]

      const heatmapData = []
      scenarios.forEach((scenario, i) => {
        timeSlots.forEach((timeSlot, j) => {
          const item = data.find(d => d.scenario === scenario && d.timeSlot === timeSlot)
          if (item) {
            heatmapData.push([j, i, item.watch_count || 0])
          }
        })
      })

      const option = {
        tooltip: {
          position: 'top',
          formatter: function(params) {
            const scenario = scenarios[params.value[1]]
            const timeSlot = timeSlots[params.value[0]]
            const item = data.find(d => d.scenario === scenario && d.timeSlot === timeSlot)
            return `场景: ${scenario}<br/>时段: ${timeSlot}<br/>观看次数: ${item.watch_count}<br/>平均时长: ${item.avg_duration}分钟`
          }
        },
        grid: {
          height: '80%',
          top: '10%'
        },
        xAxis: {
          type: 'category',
          data: timeSlots,
          splitArea: {
            show: true
          },
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'category',
          data: scenarios,
          splitArea: {
            show: true
          }
        },
        visualMap: {
          min: 0,
          max: Math.max(...data.map(item => item.watch_count)),
          calculable: true,
          orient: 'horizontal',
          left: 'center',
          bottom: '0%'
        },
        series: [{
          name: '观看热度',
          type: 'heatmap',
          data: heatmapData,
          label: {
            show: true
          },
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      }
      this.charts.watchHeatmap.setOption(option)
    },

    // 5. 内容偏好桑基图
    renderContentPreferenceChart() {
      const data = this.dashboardData.contentPreference || []
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{b} → {c} : {c}'
        },
        series: {
          type: 'sankey',
          layout: 'none',
          emphasis: {
            focus: 'adjacency'
          },
          data: this.getSankeyNodes(data),
          links: data.map(item => ({
            source: item.source,
            target: item.target,
            value: item.value
          })),
          lineStyle: {
            color: 'gradient',
            curveness: 0.5
          }
        }
      }
      this.charts.contentPreference.setOption(option)
    },

    // 6. 用户生命周期分析
    renderUserLifecycleChart() {
      const data = this.dashboardData.userLifecycle || []
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(param => {
              if (param.seriesName === '平均付费') {
                result += param.seriesName + ': ¥' + param.value + '元<br/>';
              } else if (param.seriesName === '平均完播率') {
                result += param.seriesName + ': ' + param.value + '%<br/>';
              } else {
                result += param.seriesName + ': ' + param.value + '<br/>';
              }
            });
            return result;
          }
        },
        legend: {
          data: ['用户数量', '平均付费', '平均完播率']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map(item => item.lifecycle_stage)
        },
        yAxis: [{
          type: 'value',
          name: '用户数量',
          position: 'left'
        }, {
          type: 'value',
          name: '金额(元)/百分比',
          position: 'right'
        }],
        series: [
          {
            name: '用户数量',
            type: 'bar',
            data: data.map(item => item.user_count)
          },
          {
            name: '平均付费',
            type: 'line',
            yAxisIndex: 1,
            data: data.map(item => item.avg_payment)
          },
          {
            name: '平均完播率',
            type: 'line',
            yAxisIndex: 1,
            data: data.map(item => item.avg_completion_rate)
          }
        ]
      }
      this.charts.userLifecycle.setOption(option)
    },

    // 7. 收入贡献度帕累托图
    renderRevenueContributionChart() {
      const data = this.dashboardData.revenueContribution || []
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          formatter: function(params) {
            let result = params[0].name + '<br/>';
            params.forEach(param => {
              if (param.seriesName === '收入金额') {
                result += param.seriesName + ': ¥' + param.value + '元<br/>';
              } else {
                result += param.seriesName + ': ' + param.value + '%<br/>';
              }
            });
            return result;
          }
        },
        legend: {
          data: ['收入金额', '累计占比']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: data.map((item, index) => `用户${item.user_id}`)
        },
        yAxis: [{
          type: 'value',
          name: '收入金额(元)',
          position: 'left'
        }, {
          type: 'value',
          name: '累计占比',
          min: 0,
          max: 100,
          position: 'right',
          axisLabel: {
            formatter: '{value}%'
          }
        }],
        series: [
          {
            name: '收入金额',
            type: 'bar',
            data: data.map(item => item.total_payment)
          },
          {
            name: '累计占比',
            type: 'line',
            yAxisIndex: 1,
            data: data.map(item => item.cumulative_percentage)
          }
        ]
      }
      this.charts.revenueContribution.setOption(option)
    },

    // 工具方法
    getTierColor(tier) {
      const colors = {
        '忠实粉丝': '#e74c3c',
        '重度用户': '#e67e22',
        '中度用户': '#f1c40f',
        '轻度用户': '#2ecc71'
      }
      return colors[tier] || '#3498db'
    },

    getSankeyNodes(data) {
      const nodes = []
      data.forEach(item => {
        if (!nodes.find(n => n.name === item.source)) {
          nodes.push({ name: item.source })
        }
        if (!nodes.find(n => n.name === item.target)) {
          nodes.push({ name: item.target })
        }
      })
      return nodes
    },

    // 交互功能
    refreshData() {
      this.loadData()
      this.$message.success('数据刷新成功')
    },

    exportData() {
      this.$message.info('导出功能开发中...')
    },

    handleResize() {
      Object.values(this.charts).forEach(chart => {
        if (chart) chart.resize()
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
  background: linear-gradient(135deg, #fef5e7 0%, #fdf6ec 100%);
  min-height: calc(100vh - 84px);
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: linear-gradient(90deg, #f6d365 0%, #ffffff 100%);
  padding: 30px;
  border-radius: 10px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-left {
  flex: 1;
}

.header-left h1 {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
}

.header-left p {
  font-size: 16px;
  color: #303133;
  opacity: 0.9;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-right .el-button {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.header-right .el-button:hover {
  transform: translateY(-2px);
}

.header-right .el-select {
  width: 120px;
}

.overview-cards {
  margin-bottom: 20px;
}

.stats-card {
  border-radius: 8px;
  border: none;
  background: linear-gradient(135deg, #ffffff 0%, #fef9f3 100%);
}

.stats-content {
  display: flex;
  align-items: center;
  padding: 10px;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: white;
}

.user-icon { background: #3498db; }
.revenue-icon { background: #2ecc71; }
.payment-icon { background: #e74c3c; }
.completion-icon { background: #f39c12; }

.stats-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
  border: none;
  height: 100%;
  background: linear-gradient(135deg, #ffffff 0%, #fef9f3 100%);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
  color: #303133;
}

.chart-container {
  width: 100%;
}
</style>
